import axios from 'axios'
import router from '@/router'
import { useUserStore } from '@/store/modules/user'
import { useCartStore } from '@/store/modules/cart'
import { useOrderStore } from '@/store/modules/order'

// 使用 vant 组件
// @ts-ignore
import { showLoadingToast, showToast } from 'vant'

const httpRequestInstance = axios.create({
  baseURL: import.meta.env.VITE_SERVER+import.meta.env.VITE_APP_BASE_API,
  timeout: 5000
})

let loadingInstance:any = null

// axios请求拦截器
httpRequestInstance.interceptors.request.use(config => {
  // 加载提示框
  loadingInstance = showLoadingToast({
    message: '拼命加载中',
    // background: 'rgba(0, 0, 0, 0.8)'
  })

  // 创建账户store，将账户信息使用pinia管理
  const userStore = useUserStore()
  if (userStore.profile?.token) {
    config.headers.Authorization = 'Bearer ' + userStore.profile.token
  }

  return config
}, error => {
  // 关闭加载提示
  loadingInstance.close()
  return Promise.reject(error)
})

// axios响应式拦截器
httpRequestInstance.interceptors.response.use(response => {
  // 用户存储
  const userStore = useUserStore()

  // 购物车存储
  const cartStore = useCartStore()

  // 订单存储
  const orderStore = useOrderStore()

  // 关闭加载提示
  loadingInstance.close()
  const result = response.data
  if (result.code != 200) {
    // token错误、过期
    if (result.code == 401 || result.code == 402 || result.code == 407) {
      // 清空用户信息
		  userStore.clearProfile()

      // 清空收货地址信息
      userStore.clearDeliveryAddr()

      // 清空订单信息
      orderStore.clearCreateOrderParams()

      // 清空购物车信息
      cartStore.clearCart()
      
      router.push({path: '/passwordLogin'})
    } else {
      showToast(result.message)
    }

    return Promise.reject(new Error(result.message || 'Error'))
  }
    
  return result
}, error => {
  // 关闭加载提示
  loadingInstance.close()
  console.log('err' + error) // for debug
  showToast(error)
  return Promise.reject(error)
})

export default httpRequestInstance
